/*
 * 设置图片的默认加载行为
 *
 * native 需要实现的接口有:
 * String readImageCache(String url);
 * boolean isAutoLoadImage();
 * void loadImage(String url);
 * void openImage(String urls, int index);
 *
 * native 可以调用的方法有:
 * void onImageLoadFailed(String url);
 * void onImageLoadSuccess(String url, String localUrl);
 */

var IMAGE_HOLDER_CLICK_TO_LOAD_URL = 'file:///android_asset/webview/res/image_failed.png';
var IMAGE_HOLDER_LOAD_FAILED_URL = 'file:///android_asset/webview/res/image_failed.png';
var IMAGE_HOLDER_LOADING_URL = 'file:///android_asset/webview/res/image_loading.png';

function findImageByUrl(url) {
	return $('img[original-src="' + url + '"]');
}

function onImageLoadFailed(url) {
	var image = findImageByUrl(url);
	if (image) {
		image.attr('src', IMAGE_HOLDER_LOAD_FAILED_URL);
	}
}

function onImageLoadSuccess(url, localUrl) {
	var image = findImageByUrl(url);
	if (image) {
		image.removeClass('image-holder');
		image.attr('src', localUrl);
	}
}


function setupImage(callOpenImage) {
	var urls = [];
	$('img').each(function() {
		var image = $(this);
		var originalUrl = image.attr('src');
		urls.push(originalUrl);
		image.attr('original-src', originalUrl);
        image.addClass('image-holder');
        image.attr('src', IMAGE_HOLDER_LOADING_URL);
        image.unveil(200, function() {
        	var cacheUrl = ImageBridge.readImageCache(originalUrl);
            if(cacheUrl){
                image.attr('src', cacheUrl);
            }else{
                ImageBridge.loadImage(originalUrl);
            }
        });
	});

	$('img').click(function(event) {
		var image = $(this);
        if(image.hasClass("charge_user_avatar")){
            return;
        }
		var url = image.attr('src');
		var originalUrl = image.attr('original-src');
		if (url == IMAGE_HOLDER_CLICK_TO_LOAD_URL || url == IMAGE_HOLDER_LOAD_FAILED_URL) {
			image.attr('src', IMAGE_HOLDER_LOADING_URL);
			ImageBridge.loadImage(originalUrl);
			event.preventDefault();
			event.stopPropagation();
			return;
		}

		if (callOpenImage) {
			var count = 0;
			var index = 0;
			$('img').each(function() {
				var that = $(this);
				if (event.target === this) {
                    index = count;
                }
                count++;
			});

			ImageBridge.openImage(JSON.stringify(urls), index);
			event.preventDefault();
			event.stopPropagation();
		}
	});
}